window.orderListAction = {
    init: function() {
        this.orderListView = $("#orderListView");
        if (this.orderListView.hasClass('inited')) {
            this.refresh();
            return;
        }
        this.orderListView.addClass('inited');
        console.log('orderListView init');

        this.setTab();
        this.loading = false;
        this.getList();
        this.changeList();
        this.pullRefresh();

        this.setOrderType();
    },
    refresh: function() {
        console.log('orderListView refresh');

        if (this.tabMenu) {
            this.tabMenu.update();
        } else {
            this.setTab();
        }
    },
    setTab: function() {
        var orderListTab = $("#orderListTab");
        this.tabMenu = F7.swiper('#orderListTab', {
            slidesPerView: 'auto',
            spaceBetween: 12,
            freeMode: true,
            onInit: function(swiper) {
                orderListTab.find('.swiper-slide').eq(0).addClass('on');
                swiper.slideTo(swiper.slides.length - 1);
                setTimeout(function() {
                    swiper.slideTo(0);
                }, 1000);
            },
            onTap: function(swiper, ev) {
                var idx = swiper.clickedIndex;
                orderListTab.find('.swiper-slide').eq(idx).addClass('on').siblings().removeClass('on');
                swiper.slideTo(idx - 1);
            }
        });
    },
    changeList: function() {
        var that = this;
        $("#orderListTab").on('click', '.swiper-slide', function() {
            var self = $(this);
            that.params = {
                orderState: self.data('status')
            };
            that.getList();
        });
    },
    pageSize: 10,
    getList: function(append) {
        F7.showIndicator();
        var that = this;
        var orderList = $("#orderList"),
            currentPage = orderList.find(".card").last().attr("curPage");
        console.log(currentPage);
        currentPage = currentPage ? parseInt(currentPage) + 1 : 1;
        currentPage = append ? currentPage : 1;
        var queryParams = {
            pageSize: that.pageSize,
            currentPage: currentPage
        };

        $.extend(queryParams, that.params || {});

        $.extend(queryParams, loginAction.loginParams());
        console.log(queryParams);

        var def = appXhr.POST('/order/list', queryParams)
            .done(function(data) {
                var dataContent = JSON.parse(data.content);
                var newData = {};
                for (var i = 0; i < dataContent.length; i++) {
                    newData[dataContent[i].orderNo] = dataContent[i];
                }
                console.log("newData");
                console.log(newData);
                var orderListData = {
                    list: dataContent
                };
                if (data.code === 100) {
                    if (append) {
                        console.log('append');
                        app.tplManager({
                            tplEl: "#orderListTpl",
                            renderEl: "#orderList",
                            renderData: orderListData,
                            isAppend: true
                        });

                        $.extend(that.listData, newData);

                    } else {
                        console.log('init or refresh');
                        app.tplManager({
                            tplEl: "#orderListTpl",
                            renderEl: "#orderList",
                            renderData: orderListData
                        });
                        $("#orderList").parent().scrollTop(0);
                        $$('.infinite-scroll-preloader').removeClass('hide');
                        F7.attachInfiniteScroll($$('.infinite-scroll'));
                        that.listData = newData;
                    }
                    orderList.find('.card').last().attr('curPage', currentPage);
                    // console.log(that.listData);
                    that.infinite();
                }
            })
            .fail(function() {
                that.loading = false;
            });

        return def;
    },
    // 下拉刷新
    pullRefresh: function() {
        var that = this;

        // Pull to refresh content
        var ptrContent = $$('.pull-to-refresh-content');

        // Add 'refresh' listener on it
        ptrContent.on('refresh', function(e) {
            that.getList().done(function() {
                F7.pullToRefreshDone();
            });
        });
    },
    // 上拉加载
    infinite: function() {
        var that = this;
        // Loading flag
        // var loading = false;

        var orderList = $("#orderList");
        // Last loaded index
        var lastIndex = orderList.find('.card').length;

        /*console.log("lastIndex");
        console.log(lastIndex);*/

        /* if (lastIndex < that.pageSize) {
             $$('.infinite-scroll-preloader').remove();
         }*/

        // Attach 'infinite' event handler
        $$('.infinite-scroll').on('infinite', function() {
            /*console.log("loading");
            console.log(that.loading);*/
            // Exit, if loading in progress
            if (that.loading) return;

            // Set loading flag
            that.loading = true;
            that.getList(true).done(function(data) {

                if (!data.content || data.content.length === 0) {
                    F7.detachInfiniteScroll($$('.infinite-scroll'));
                    // $$('.infinite-scroll-preloader').addClass('hide');
                }

                lastIndex = orderList.find('.card').length;
                that.loading = false;

            });


        });
    },
    setOrderType: function() {

        var orderListType = localStorage.getItem('orderListType');
        orderListType = orderListType ? orderListType : 'createTime';
        var listData = [{
            value: 'createTime',
            text: '下单时间'
        }, {
            value: 'receiveTime',
            text: '接单时间'
        }, {
            value: 'commitTime',
            text: '提交时间'
        }, {
            value: 'sendTime',
            text: '派车时间'
        }, {
            value: 'startTime',
            text: '装货时间'
        }, {
            value: 'endTime',
            text: '卸货时间'
        }, {
            value: 'signTime',
            text: '签收时间'
        }, {
            value: 'cancelTime',
            text: '取消时间'
        }, {
            value: 'kmNum',
            text: '公里数'
        }];
        var listHtml = '';

        listData.forEach(function(element, index) {
            var isSelected = orderListType === element.value ? ' checked="checked"' : '';
            listHtml += '<li>' +
                '<label class="label-radio item-content">' +
                '<input type="radio" name="orderTypeRadio" value="' + element.value + '" ' + isSelected + '>' +
                '<div class="item-inner">' +
                '<div class="item-title">' + element.text + '</div>' +
                '</div>' +
                '</label>' +
                '</li>';
        });
        

        $("#setOrderType").on('click', function() {
            F7.modal({
                title: '选择排序规则',
                text: '<div class="list-block h240 overflow-auto"><ul id="pickerBody">' + listHtml +'</ul></div>',
                buttons: [{
                    text: '取消'
                }, {
                    text: 'Ok, got it',
                    bold: true
                }]
            });

            $('#pickerBody').on('click', '.label-radio', function() {
                console.log($(this).find('[name="orderTypeRadio"]').val());
                localStorage.setItem('orderListType', $(this).find('[name="orderTypeRadio"]').val());
            });
        });
    }
};

module.exports = orderListAction;
